package de.havre.wakeupnas.nas;

import java.awt.Desktop;
import java.io.File;
import java.util.Timer;

import de.havre.wakeupnas.Config;
import de.havre.wakeupnas.sync.SyncProcess;

public class NasController {

	private SyncProcess snyc;

	private NasState state;

	private Timer timer;

	private NasStateListener nasStateListener;

	private boolean startSync;

	private NasState bevorSyncState;;

	public NasController() {
		state = NasState.OFF;
	}

	public void registerNasStateListener(NasStateListener listener) {
		nasStateListener = listener;
		nasStateListener.notifyNasState(state);
	}

	public void switchOff() {
		if (state.equals(NasState.ON) || state.equals(NasState.READY)
				|| state.equals(NasState.SYNC)) {
			state = NasState.OFF;
			timer.cancel();
			nasStateListener.notifyNasState(state);
			if (snyc != null) {
				snyc.stop();
				snyc = null;
			}
		}
	}

	public void switchOn() {
		if (state.equals(NasState.OFF)) {
			state = NasState.ON;
			timer = new Timer();
			timer.schedule(new NasTask(this), 10, 10000);
			nasStateListener.notifyNasState(state);
		}
	}

	public void startSync() {

		if (state.equals(NasState.OFF)) {
			switchOn();
			startSync = true;
			bevorSyncState = NasState.OFF;
			nasStateListener.notifyInfo("Wait until NAS is ready");
		} else if (state.equals(NasState.ON)) {
			startSync = true;
			bevorSyncState = NasState.READY;
			nasStateListener.notifyInfo("Wait until NAS is ready");
		} else if (state.equals(NasState.READY)) {
			state = NasState.SYNC;
			nasStateListener.notifyNasState(state);
			bevorSyncState = NasState.READY;
			snyc = new SyncProcess(this);
			snyc.start();
			nasStateListener.notifyInfo("Sync is stared!");
		}
	}

	public NasState getState() {
		return state;
	}

	protected void notifyNasIsOnline() {

		if (state.equals(NasState.ON)) {
			if (startSync) {
				startSync = false;
				state = NasState.SYNC;
				snyc = new SyncProcess(this);
				snyc.start();
				nasStateListener.notifyInfo("NAS is Online! Sync is stared!");
			} else {
				state = NasState.READY;
				showFolder();
				nasStateListener.notifyInfo("NAS is online!");
			}
			nasStateListener.notifyNasState(state);
		}
	}

	public void notifySyncFinished(String info) {
		snyc = null;
		nasStateListener.notifyInfo(info);
		if (bevorSyncState.equals(NasState.OFF)) {
			switchOff();
		} else {
			state = bevorSyncState;
			nasStateListener.notifyNasState(state);
		}
	}

	public void showFolder() {
		try {
			String folder = (String) Config.getProperties().get("checkfile");
			Desktop desktop = Desktop.getDesktop();
			File file = new File(folder);
			desktop.browse(file.toURI());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
